<template>
  <div class="gi_page">
    <a-spin :loading="loading">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        auto-label-width
        label-align="left"
        :layout="width >= 500 ? 'horizontal' : 'vertical'"
        :disabled="!isUpdate"
        scroll-to-first-error
        class="form"
      >
        <a-form-item
          field="corpID"
          label="企业Corpid"
          help="每个企业都拥有唯一的corpid，获取此信息可在管理后台“我的企业”－“企业信息”下查看“企业ID”"
          hide-asterisk
        >
          <a-input v-model.trim="form.corpID" />
        </a-form-item>
        <a-form-item
          field="agentID"
          label="应用agentid"
          help="每个应用都有唯一的agentid。在管理后台->“应用管理”->“应用”，点进某个应用，即可看到agentid"
          hide-asterisk
        >
          <a-input v-model.trim="form.agentID" />
        </a-form-item>
        <a-form-item
          field="secret"
          label="应用钥匙secret"
          help="secret是企业应用里面用于保障数据安全的“钥匙”，每一个应用都有一个独立的访问密钥，为了保证数据的安全，secret务必不能泄漏。"
          hide-asterisk
        >
          <a-input v-model.trim="form.secret" />
        </a-form-item>

        <a-form-item
          label="缓存类型"
          help="支持缓存方式：内存缓存和Redis缓存"
          hide-asterisk
        >
          <a-radio-group v-model="form.type" type="button">
            <a-radio value="local">本地内存</a-radio>
            <a-radio value="redis">Redis</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="form.type === 'redis'"
          field="redis.addr"
          label="Redis地址"
          hide-asterisk
        >
          <a-input v-model.trim="form.redis.addr" />
        </a-form-item>
        <a-form-item
          v-if="form.type === 'redis'"
          field="password"
          label="Redis密码"
          hide-asterisk
        >
          <a-input-password v-model.trim="form.password" autocomplete="off" />
        </a-form-item>
        <a-form-item
          v-if="form.type === 'redis'"
          label="redis.db"
          field="db"
          help="reids服务器连接端口"
          hide-asterisk
        >
          <a-input-number v-model="form.redis.db" :min="0" />
        </a-form-item>

        <a-space style="margin-bottom: 16px">
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" type="primary" @click="onUpdate">
            <template #icon><icon-edit /></template>修改
          </a-button>
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" @click="onResetValue">
            <template #icon><icon-undo /></template>恢复默认
          </a-button>
          <a-button v-if="isUpdate" type="primary" @click="handleSave">
            <template #icon><icon-save /></template>保存
          </a-button>
          <a-button v-if="isUpdate" @click="reset">
            <template #icon><icon-refresh /></template>重置
          </a-button>
          <a-button v-if="isUpdate" @click="handleCancel">
            <template #icon><icon-undo /></template>取消
          </a-button>
        </a-space>
      </a-form>
    </a-spin>
    <a-alert v-if="isAlert" :type="alerttype">{{ alertText }}</a-alert>
  </div>
</template>

<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'
import { type FormInstance, Message, Modal } from '@arco-design/web-vue'
import {
  CheckHealth,
  GetDataSource,
  UpdateDataSource,
} from '@/apis/plugin/datasource'
import { useResetReactive } from '@/hooks'
import { encryptByRsa } from '@/utils/encrypt'

defineOptions({ name: 'SystemMailConfig' })
const { width } = useWindowSize()
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const [form] = useResetReactive({
  id: '',
  version: '',
  name: '',
  corpID: '',
  agentID: '',
  secret: '',
  password: '',
  type: '',
  redis: {
    addr: '',
    db: 0,
  },
})
const rules: FormInstance['rules'] = {
  corpID: [{ required: true, message: '请输入值' }],
  agentID: [{ required: true, message: '请输入值' }],
  secret: [{ required: true, message: '请输入值' }],
  addr: [{ required: true, message: '请输入值' }],
  password: [{ required: true, message: '请输入值' }],

}
const isAlert = ref(false)
const alerttype = ref('success')
const alertText = ref('')
// 重置
const reset = () => {
  formRef.value?.resetFields()
}

const isUpdate = ref(false)
// 修改
const onUpdate = () => {
  isUpdate.value = true
}

// 取消
const handleCancel = () => {
  reset()
  isUpdate.value = false
}

// 查询列表数据
const getDataList = async () => {
  loading.value = true
  const { data } = await GetDataSource('wework')
  Object.assign(form, data.jsonData)
  form.id = data.id
  form.version = data.version
  form.name = data.name
  form.type = 'local'
  if (form.redis.addr !== '') {
    form.type = 'redis'
  }
  loading.value = false
}

// 保存
const handleSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) return false
  const formData = ref({
    id: form.id,
    name: form.name,
    version: form.version,
    remark: '邮件配置',
    securejsonData: '',
    jsondata: {
      corpID: form.corpID,
      agentID: form.agentID,
      // secret: form.secret,
      redis: {
        addr: form.redis.addr,
        db: form.redis.db,
      },
    },
  })
  if (form.type === 'local') {
    formData.value.jsondata.redis = {
      addr: '',
      db: 0,
    }
  }
  formData.value.securejsonData = JSON.stringify({ secret: encryptByRsa(form.secret), redisPassword: encryptByRsa(form.password) })
  await UpdateDataSource(formData.value)
  await getDataList()
  Message.success('保存设置成功')
  // 检查健康状态
  const result = await CheckHealth('email')
  isAlert.value = true
  if (result.success) {
    isAlert.value = true
    alerttype.value = 'success'
    alertText.value = '配置成功'
  } else {
    alerttype.value = 'error'
    alertText.value = `配置失败，原因:${result.msg}`
  }
}

// 恢复默认
const handleResetValue = async () => {
  Message.success('恢复成功')
  await getDataList()
}
const onResetValue = () => {
  Modal.warning({
    title: '警告',
    content: '确认恢复配置为默认值吗？',
    hideCancel: false,
    maskClosable: false,
    onOk: handleResetValue,
  })
}

onMounted(() => {
  getDataList()
})
</script>

<style scoped lang="scss">
:deep(.arco-form-item.arco-form-item-has-help) {
  margin-bottom: 5px;
}

:deep(.form .arco-input-wrapper),
:deep(.arco-select-view-single) {
  width: 220px;
}
</style>
